package me.zhengjie.modules.fund.service.impl;

import lombok.extern.slf4j.Slf4j;
import me.zhengjie.modules.fund.domain.UserFundLog;
import me.zhengjie.modules.fund.repository.UserFundLogRepository;
import me.zhengjie.modules.fund.service.UserFundLogService;
import me.zhengjie.modules.fund.service.dto.UserFundLogQueryCriteria;
import me.zhengjie.utils.QueryHelp;
import me.zhengjie.utils.ValidationUtil;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;

@Slf4j
@Service
public class UserFundLogServiceImpl implements UserFundLogService {

    @Resource
    private UserFundLogRepository userFundLogRepository;

    /**
     * @param resources
     * @see UserFundLogService#create(UserFundLog)
     */
    @Override
    public void create(UserFundLog resources) {
        userFundLogRepository.save(resources);
    }

    /**
     * @param resources
     * @see UserFundLogService#update(UserFundLog)
     */
    @Override
    public void update(UserFundLog resources) {
        UserFundLog userFundLog = userFundLogRepository.findById(resources.getId()).orElseGet(UserFundLog::new);
        ValidationUtil.isNull(userFundLog.getId(), "UserFundLog", "id", resources.getId());
        userFundLogRepository.save(resources);
    }

    /**
     * @param resources
     * @see UserFundLogService#save(UserFundLog)
     */
    @Override
    public void save(UserFundLog resources) {
        UserFundLog userFundLog = userFundLogRepository.findByUserIdAndFundCodeAndDate(resources.getUserId(), resources.getFundCode(), resources.getDate());
        if (Objects.isNull(userFundLog)) {
            create(resources);
        } else {
            resources.setId(userFundLog.getId());
            update(resources);
        }
    }

    @Override
    public List<UserFundLog> queryAll(UserFundLogQueryCriteria queryCriteria) {
        List<UserFundLog> logs = userFundLogRepository.findAll((root, criteriaQuery, queryBuilder) -> QueryHelp.getPredicate(root, queryCriteria, queryBuilder));
        return logs;
    }
}
